const express = require("express");
const router = express.Router();
const { User } = require("../../models");
const { success, failure } = require("../../utils/response");
const { Op } = require("sequelize");
const {
  NotFound,
  Unauthorized,
  BadRequest,
} = require('http-errors');
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");

router.post("/login", async (req, res) => {
  try {
    const { login, password } = req.body;
    if (!login) {
      throw new BadRequest("请输入用户名或邮箱");
    }
    if (!password) {
      throw new BadRequest("请输入密码");
    }

    const condition = {
      where: {
        [Op.or]: [{ username: login }, { email: login }],
      },
    };
    const user = await User.findOne(condition);
    if (!user) {
      throw new NotFound("用户不存在");
    }
    const isMatch = await bcrypt.compareSync(password, user.password);
    // 验证密码是否正确
    if (!isMatch) {
      throw new Unauthorized("密码错误");
    }
    // 验证是否是管理员
    if (user.role !== 100) {
      throw new Unauthorized("没有权限");
    }
    // 生成身份验证令牌
    const token = jwt.sign(
      {
        userId: user.id,
      },
      process.env.SECRET,
      { expiresIn: "30d" }
    );
    success(res, "登录成功", { token });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
